<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语音同传系统</title>
    <script src="https://unpkg.com/qrcode@1.5.3/build/qrcode.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', 'PingFang SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
            background: #f8fafc;
            min-height: 100vh;
            color: #1a202c;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            overflow-x: hidden;
            -webkit-overflow-scrolling: touch;
        }

        .header {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #ec4899 100%);
            padding: 60px 20px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }

        .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            opacity: 0.3;
        }

        .header h1 {
            color: white;
            font-size: 3.5rem;
            margin-bottom: 15px;
            font-weight: 300;
            letter-spacing: 2px;
            text-shadow: 0 4px 20px rgba(0,0,0,0.3);
            position: relative;
            z-index: 1;
        }

        .header .subtitle {
            color: rgba(255, 255, 255, 0.9);
            font-size: 1.3rem;
            font-weight: 300;
            position: relative;
            z-index: 1;
        }
        
        .main-content {
            max-width: 1000px;
            margin: -40px auto 0;
            padding: 0 20px 40px;
            position: relative;
            z-index: 2;
            min-height: calc(100vh - 200px);
        }

        .config-card {
            background: white;
            border-radius: 24px;
            padding: 40px 40px 80px 40px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            backdrop-filter: blur(20px);
            margin-bottom: 40px;
            position: relative;
            overflow: visible;
        }

        .config-title {
            text-align: center;
            font-size: 2rem;
            font-weight: 600;
            color: #1a202c;
            margin-bottom: 40px;
            position: relative;
        }

        .config-title::after {
            content: '';
            position: absolute;
            bottom: -10px;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 4px;
            background: linear-gradient(90deg, #4f46e5, #7c3aed);
            border-radius: 2px;
        }

        .language-config {
            display: grid;
            grid-template-columns: 1fr auto 1fr;
            gap: 40px;
            align-items: start;
            margin-bottom: 80px;
            padding-bottom: 40px;
        }

        .language-group {
            position: relative;
        }

        .language-group label {
            display: block;
            font-weight: 600;
            color: #4a5568;
            margin-bottom: 12px;
            font-size: 16px;
            text-align: center;
        }

        select {
            width: 100%;
            padding: 16px 20px;
            border: 2px solid #e2e8f0;
            border-radius: 16px;
            font-size: 16px;
            background: #f8fafc;
            color: #2d3748;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            appearance: none;
            background-image: url('data:image/svg+xml;charset=US-ASCII,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="%234a5568" stroke-width="2"><polyline points="6,9 12,15 18,9"></polyline></svg>');
            background-repeat: no-repeat;
            background-position: right 16px center;
            background-size: 20px;
            font-weight: 500;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }

        select:hover {
            border-color: #4f46e5;
            background: white;
            transform: translateY(-1px);
            box-shadow: 0 8px 25px rgba(79, 70, 229, 0.15);
        }

        select:focus {
            outline: none;
            border-color: #4f46e5;
            background: white;
            box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
            transform: translateY(-2px);
        }

        .arrow {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            border-radius: 50%;
            color: white;
            font-size: 24px;
            font-weight: bold;
            box-shadow: 0 8px 25px rgba(79, 70, 229, 0.3);
            position: relative;
            margin: 0 auto;
            animation: pulse 2s infinite;
        }

        .arrow::before {
            content: '';
            position: absolute;
            top: -2px;
            left: -2px;
            right: -2px;
            bottom: -2px;
            background: linear-gradient(135deg, #4f46e5, #7c3aed, #ec4899);
            border-radius: 50%;
            z-index: -1;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .arrow:hover::before {
            opacity: 1;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }

        .multi-select-container {
            position: relative;
            width: 100%;
            z-index: 100;
        }

        .selected-languages {
            width: 100%;
            min-height: 60px;
            padding: 16px 20px;
            border: 2px solid #e2e8f0;
            border-radius: 16px;
            background: #f8fafc;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            position: relative;
        }

        .selected-languages::after {
            content: '';
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            width: 0;
            height: 0;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            border-top: 8px solid #4a5568;
            transition: transform 0.3s ease;
        }

        .selected-languages.active::after {
            transform: translateY(-50%) rotate(180deg);
        }

        .selected-languages:hover {
            border-color: #4f46e5;
            background: white;
            transform: translateY(-1px);
            box-shadow: 0 8px 25px rgba(79, 70, 229, 0.15);
        }

        .selected-languages.active {
            border-color: #4f46e5;
            background: white;
            box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
        }

        .placeholder {
            color: #a0aec0;
            font-style: normal;
            font-weight: 500;
        }

        .language-tag {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            padding: 8px 16px;
            border-radius: 25px;
            font-size: 14px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
            transition: all 0.3s ease;
        }

        .language-tag:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(79, 70, 229, 0.4);
        }

        .language-tag .remove {
            cursor: pointer;
            font-weight: bold;
            opacity: 0.8;
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .language-tag .remove:hover {
            opacity: 1;
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }

        .language-options {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 2px solid #4f46e5;
            border-radius: 16px;
            box-shadow: 0 12px 40px rgba(79, 70, 229, 0.25);
            z-index: 9999;
            max-height: 300px;
            overflow-y: auto;
            display: none;
            margin-top: 4px;
        }

        .language-options.show {
            display: block;
        }

        .language-option {
            padding: 12px 16px;
            cursor: pointer;
            transition: background-color 0.2s;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .language-option:hover {
            background-color: #f8f9ff;
        }

        .language-option input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .language-option label {
            cursor: pointer;
            flex: 1;
            margin: 0;
        }
        
        .controls {
            display: flex;
            gap: 20px;
            justify-content: center;
            margin-top: 40px;
        }

        .control-btn {
            padding: 18px 36px;
            border: none;
            border-radius: 50px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
            min-width: 160px;
            letter-spacing: 0.5px;
            color: #666 !important;
        }

        .control-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }

        .control-btn:hover::before {
            left: 100%;
        }

        .control-btn:active {
            transform: translateY(-1px);
        }

        .control-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .start-btn {
            background: linear-gradient(135deg, #10b981, #059669);
            color: #666 !important;
            box-shadow: 0 8px 25px rgba(16, 185, 129, 0.3);
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
        }

        .start-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 35px rgba(16, 185, 129, 0.4);
            color: #666 !important;
        }

        .start-btn:disabled {
            background: linear-gradient(135deg, #9ca3af, #6b7280);
            color: rgba(255, 255, 255, 0.7) !important;
        }

        .stop-btn {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: #666 !important;
            box-shadow: 0 8px 25px rgba(239, 68, 68, 0.3);
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
        }

        .stop-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 35px rgba(239, 68, 68, 0.4);
            color: #666 !important;
        }

        .stop-btn:disabled {
            background: linear-gradient(135deg, #9ca3af, #6b7280);
            color: red !important;
        }
        
        .status-bar {
            text-align: center;
            padding: 15px;
            margin: 20px;
            border-radius: 10px;
            font-weight: bold;
            font-size: 16px;
        }
        
        .status-connected {
            background: rgba(76, 175, 80, 0.1);
            color: #2e7d32;
            border: 2px solid #4CAF50;
        }
        
        .status-recording {
            background: rgba(255, 193, 7, 0.1);
            color: #f57f17;
            border: 2px solid #FFC107;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }
        

        
        .item-timestamp {
            font-size: 12px;
            color: #999;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .item-timestamp::before {
            content: '🕐';
            font-size: 14px;
        }

        .original-text {
            font-size: 20px;
            line-height: 1.6;
            color: #2c3e50;
            margin-bottom: 15px;
            font-weight: 500;
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }

        .original-text::before {
            content: '🎤';
            font-size: 18px;
            margin-top: 2px;
            flex-shrink: 0;
        }

        .translations-container {
            margin-top: 15px;
        }

        .translation-item-single {
            font-size: 18px;
            line-height: 1.6;
            color: #764ba2;
            background: linear-gradient(135deg, #f8f9ff, #f0f2ff);
            padding: 15px;
            border-radius: 10px;
            border-left: 4px solid #764ba2;
            margin-bottom: 10px;
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }

        .translation-item-single::before {
            content: '🔄';
            font-size: 16px;
            margin-top: 2px;
            flex-shrink: 0;
        }

        .translation-lang-header {
            font-size: 14px;
            font-weight: bold;
            color: #666;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .translation-text {
            font-size: 16px;
            line-height: 1.5;
            color: #333;
        }

        .language-indicator {
            font-size: 12px;
            color: #666;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .empty-state {
            text-align: center;
            color: #999;
            font-size: 18px;
            margin-top: 100px;
        }

        .empty-state::before {
            content: '🎙️';
            font-size: 48px;
            display: block;
            margin-bottom: 20px;
        }

        /* 全屏同传大屏样式 */
        .fullscreen-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 50%, #0a0a0a 100%);
            z-index: 9999;
            display: none;
            flex-direction: column;
            color: white;
            font-family: 'Microsoft YaHei', 'PingFang SC', Arial, sans-serif;
            overflow: hidden;
        }

        .fullscreen-overlay.show {
            display: flex;
        }

        /* 顶部控制栏 */
        .fullscreen-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 40px;
            background: rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .fullscreen-title {
            font-size: 24px;
            font-weight: bold;
            color: #ffffff;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #ff4444;
            animation: pulse 2s infinite;
        }

        .status-indicator.recording {
            background: #44ff44;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .fullscreen-controls {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .control-btn {
            padding: 10px 20px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            backdrop-filter: blur(10px);
        }

        .control-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.5);
            transform: translateY(-2px);
        }

        .control-btn.stop {
            background: rgba(255, 68, 68, 0.2);
            border-color: rgba(255, 68, 68, 0.5);
        }

        .control-btn.stop:hover {
            background: rgba(255, 68, 68, 0.3);
        }

        /* 主显示区域 - 左右分栏布局 */
        .fullscreen-content {
            flex: 1;
            display: flex;
            flex-direction: row;
            height: calc(100vh - 80px);
            overflow: hidden;
        }

        /* 左侧 - 实时语音识别区域 */
        .speech-recognition-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 40px;
            border-right: 1px solid rgba(255, 255, 255, 0.1);
            background: linear-gradient(135deg, rgba(68, 68, 255, 0.1), rgba(68, 255, 68, 0.1));
        }

        .speech-panel-header {
            font-size: 24px;
            color: rgba(255, 255, 255, 0.9);
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: bold;
        }

        .speech-content {
            flex: 1;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 20px;
            padding: 30px;
            overflow-y: auto;
            backdrop-filter: blur(15px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            scrollbar-width: thin;
            scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
        }

        .speech-content::-webkit-scrollbar {
            width: 6px;
        }

        .speech-content::-webkit-scrollbar-track {
            background: transparent;
        }

        .speech-content::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 3px;
        }

        .speech-text {
            font-size: 20px;
            line-height: 1.8;
            color: #ffffff;
            font-weight: 400;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
            white-space: pre-wrap;
            word-wrap: break-word;
            position: relative;
        }

        /* 识别中的动画指示器 */
        .speech-text::after {
            content: '';
            display: inline-block;
            width: 3px;
            height: 20px;
            background: #44ff44;
            margin-left: 5px;
            animation: blink 1s infinite;
            opacity: 0;
        }

        .speech-text.recognizing::after {
            opacity: 1;
        }

        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0; }
        }

        /* 打字机效果 */
        .typing-indicator {
            display: inline-block;
            margin-left: 8px;
        }

        .typing-indicator span {
            display: inline-block;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #44ff44;
            margin: 0 2px;
            animation: typing 1.4s infinite ease-in-out;
        }

        .typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
        .typing-indicator span:nth-child(2) { animation-delay: -0.16s; }
        .typing-indicator span:nth-child(3) { animation-delay: 0s; }

        @keyframes typing {
            0%, 80%, 100% {
                transform: scale(0.8);
                opacity: 0.5;
            }
            40% {
                transform: scale(1);
                opacity: 1;
            }
        }

        /* 右侧 - 多语言翻译区域 */
        .translations-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 40px;
            background: linear-gradient(135deg, rgba(118, 75, 162, 0.1), rgba(255, 68, 68, 0.1));
        }

        .translations-panel-header {
            font-size: 24px;
            color: rgba(255, 255, 255, 0.9);
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: bold;
        }

        .translations-container {
            flex: 1;
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
        }

        .translations-container::-webkit-scrollbar {
            width: 6px;
        }

        .translations-container::-webkit-scrollbar-track {
            background: transparent;
        }

        .translations-container::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 3px;
        }

        /* 单个语言翻译区域 */
        .language-translation-block {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            transition: all 0.3s ease;
        }

        .language-translation-block:hover {
            background: rgba(255, 255, 255, 0.08);
            border-color: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        .language-header {
            font-size: 18px;
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: bold;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            padding-bottom: 10px;
        }

        .language-text {
            font-size: 16px;
            line-height: 1.6;
            color: rgba(255, 255, 255, 0.9);
            white-space: pre-wrap;
            word-wrap: break-word;
            min-height: 50px;
            position: relative;
        }

        .language-text::after {
            content: '';
            display: inline-block;
            width: 2px;
            height: 16px;
            background: #667eea;
            margin-left: 5px;
            animation: blink 1s infinite;
            opacity: 0;
        }

        .language-text.translating::after {
            opacity: 1;
        }



        /* 音频可视化 - 波浪特效 */
        .audio-visualizer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 60px;
            overflow: hidden;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .audio-visualizer.active {
            opacity: 1;
        }

        /* 波浪效果 */
        .wave {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 200%;
            height: 100%;
            background: linear-gradient(90deg,
                rgba(68, 68, 255, 0.3) 0%,
                rgba(68, 255, 68, 0.3) 25%,
                rgba(255, 255, 68, 0.3) 50%,
                rgba(255, 68, 68, 0.3) 75%,
                rgba(68, 68, 255, 0.3) 100%);
            border-radius: 50% 50% 0 0;
            animation: wave 3s ease-in-out infinite;
        }

        .wave:nth-child(2) {
            animation-delay: -1s;
            opacity: 0.7;
            background: linear-gradient(90deg,
                rgba(102, 126, 234, 0.4) 0%,
                rgba(118, 75, 162, 0.4) 50%,
                rgba(102, 126, 234, 0.4) 100%);
        }

        .wave:nth-child(3) {
            animation-delay: -2s;
            opacity: 0.5;
            background: linear-gradient(90deg,
                rgba(255, 255, 255, 0.2) 0%,
                rgba(255, 255, 255, 0.1) 50%,
                rgba(255, 255, 255, 0.2) 100%);
        }

        @keyframes wave {
            0% {
                transform: translateX(-50%) translateY(20px);
            }
            50% {
                transform: translateX(-50%) translateY(0px);
            }
            100% {
                transform: translateX(-50%) translateY(20px);
            }
        }

        /* 音频频谱效果 */
        .audio-bars {
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            align-items: flex-end;
            height: 40px;
            gap: 3px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .audio-bars.active {
            opacity: 1;
        }

        .audio-bar {
            width: 4px;
            background: linear-gradient(to top, #44ff44, #ffff44, #ff4444);
            border-radius: 2px 2px 0 0;
            animation: audioBar 0.5s ease-in-out infinite alternate;
        }

        .audio-bar:nth-child(1) { animation-delay: 0s; }
        .audio-bar:nth-child(2) { animation-delay: 0.1s; }
        .audio-bar:nth-child(3) { animation-delay: 0.2s; }
        .audio-bar:nth-child(4) { animation-delay: 0.3s; }
        .audio-bar:nth-child(5) { animation-delay: 0.4s; }
        .audio-bar:nth-child(6) { animation-delay: 0.3s; }
        .audio-bar:nth-child(7) { animation-delay: 0.2s; }
        .audio-bar:nth-child(8) { animation-delay: 0.1s; }

        @keyframes audioBar {
            0% { height: 5px; }
            100% { height: 25px; }
        }

        /* 二维码弹窗样式 */
        .qr-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(10px);
            z-index: 10000;
            display: none;
            justify-content: center;
            align-items: center;
        }

        .qr-modal.show {
            display: flex;
        }

        .qr-modal-content {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 20px;
            padding: 40px;
            text-align: center;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            border: 2px solid rgba(255, 255, 255, 0.2);
            max-width: 400px;
            width: 90%;
            animation: modalSlideIn 0.3s ease-out;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: scale(0.8) translateY(-50px);
            }
            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        .qr-title {
            font-size: 24px;
            color: white;
            margin-bottom: 20px;
            font-weight: bold;
        }

        .qr-subtitle {
            font-size: 16px;
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 30px;
            line-height: 1.5;
        }

        .qr-code-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 30px;
            display: inline-block;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
        }

        .qr-code {
            width: 200px;
            height: 200px;
            border: none;
        }

        .qr-info {
            font-size: 14px;
            color: rgba(255, 255, 255, 0.7);
            margin-bottom: 20px;
            line-height: 1.4;
        }

        .qr-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        .qr-btn {
            padding: 12px 24px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            backdrop-filter: blur(10px);
        }

        .qr-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.5);
            transform: translateY(-2px);
        }

        .qr-btn.primary {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.5);
        }

        .qr-btn.primary:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        /* 登录页面样式 */
        .login-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #ec4899 100%);
            z-index: 10000;
            display: flex;
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(10px);
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
        }

        .login-overlay.hidden {
            display: none;
        }

        .login-container {
            background: white;
            border-radius: 24px;
            padding: 50px 40px;
            box-shadow: 0 25px 80px rgba(0, 0, 0, 0.3);
            max-width: 450px;
            width: 90%;
            text-align: center;
            position: relative;
            overflow: hidden;
            margin: 20px auto;
            min-height: auto;
        }

        .login-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 6px;
            background: linear-gradient(90deg, #4f46e5, #7c3aed, #ec4899);
        }

        .login-title {
            font-size: 2.2rem;
            font-weight: 600;
            color: #1a202c;
            margin-bottom: 10px;
        }

        .login-subtitle {
            color: #6b7280;
            font-size: 1rem;
            margin-bottom: 40px;
            line-height: 1.5;
        }

        .trial-info {
            background: linear-gradient(135deg, #f0f9ff, #e0f2fe);
            border: 2px solid #0ea5e9;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 30px;
            text-align: left;
        }

        .trial-info h3 {
            color: #0369a1;
            font-size: 1.1rem;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .trial-info p {
            color: #0c4a6e;
            margin: 8px 0;
            font-size: 0.95rem;
        }

        .trial-info .credentials {
            background: rgba(14, 165, 233, 0.1);
            border-radius: 8px;
            padding: 12px;
            margin-top: 15px;
            font-family: 'Courier New', monospace;
        }

        .form-group {
            margin-bottom: 25px;
            text-align: left;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            color: #374151;
            margin-bottom: 8px;
            font-size: 0.95rem;
        }

        .form-input {
            width: 100%;
            padding: 16px 20px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #f9fafb;
        }

        .form-input:focus {
            outline: none;
            border-color: #4f46e5;
            background: white;
            box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
        }

        .login-btn {
            width: 100%;
            padding: 16px;
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 20px;
        }

        .login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(79, 70, 229, 0.3);
        }

        .login-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .error-message {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 0.9rem;
            display: none;
        }

        .error-message.show {
            display: block;
        }

        .demo-note {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            color: #166534;
            padding: 15px;
            border-radius: 12px;
            font-size: 0.9rem;
            margin-top: 20px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .login-overlay {
                align-items: flex-start;
                padding: 20px 0;
            }

            .login-container {
                padding: 30px 20px;
                margin: 20px auto;
                width: calc(100% - 40px);
                max-width: 400px;
                min-height: auto;
                position: relative;
            }

            .login-title {
                font-size: 1.6rem;
                margin-bottom: 20px;
            }

            .form-group {
                margin-bottom: 20px;
            }

            .form-input {
                padding: 14px 16px;
                font-size: 16px;
            }

            .login-btn {
                padding: 14px;
                font-size: 16px;
            }
        }

        @media (max-width: 768px) {
            /* 全屏界面移动端优化 - 支持滚动 */
            .fullscreen-overlay {
                overflow-y: auto;
                -webkit-overflow-scrolling: touch;
            }

            .fullscreen-header {
                padding: 15px 20px;
                position: sticky;
                top: 0;
                z-index: 100;
                background: rgba(0, 0, 0, 0.5);
                backdrop-filter: blur(10px);
            }

            .fullscreen-title {
                font-size: 18px;
            }

            .fullscreen-content {
                flex-direction: column;
                height: auto;
                min-height: calc(100vh - 80px);
                overflow: visible;
                padding-bottom: 20px;
            }

            .speech-recognition-panel,
            .translations-panel {
                padding: 20px;
                min-height: 300px;
                flex: none;
            }

            .speech-recognition-panel {
                border-right: none;
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);
                margin-bottom: 20px;
            }

            .speech-panel-header,
            .translations-panel-header {
                font-size: 18px;
                margin-bottom: 15px;
                position: sticky;
                top: 80px;
                background: rgba(255, 255, 255, 0.1);
                padding: 10px;
                border-radius: 8px;
                backdrop-filter: blur(5px);
            }

            .speech-content,
            .translations-content {
                max-height: none;
                overflow: visible;
            }

            .speech-text {
                font-size: 16px;
                line-height: 1.6;
                min-height: 200px;
                padding: 15px;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 12px;
                margin-bottom: 20px;
            }

            .language-panel {
                margin-bottom: 15px;
                padding: 15px;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 12px;
            }

            .language-text {
                font-size: 14px;
                line-height: 1.5;
                min-height: 60px;
            }

            .panel-title {
                font-size: 16px;
                margin-bottom: 10px;
                font-weight: 600;
            }

            .qr-modal-content {
                padding: 30px 20px;
            }

            .qr-code {
                width: 160px;
                height: 160px;
            }

            .qr-buttons {
                flex-direction: column;
            }
        }
        

        
        .audio-visualizer {
            text-align: center;
            margin: 20px 0;
        }
        
        .audio-level {
            width: 200px;
            height: 8px;
            background: #e0e0e0;
            border-radius: 4px;
            margin: 10px auto;
            overflow: hidden;
        }
        
        .audio-level-bar {
            height: 100%;
            background: linear-gradient(90deg, #4CAF50, #FFC107, #f44336);
            width: 0%;
            transition: width 0.1s;
            border-radius: 4px;
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: rgba(255, 255, 255, 0.8);
            font-size: 14px;
        }
        
        @media (max-width: 768px) {
            body {
                padding: 0;
                margin: 0;
                overflow-x: hidden;
                -webkit-overflow-scrolling: touch;
            }

            .header {
                padding: 40px 15px;
            }

            .header h1 {
                font-size: 2.5rem;
            }

            .main-content {
                margin: -20px auto 0;
                padding: 0 15px 140px;
                min-height: calc(100vh - 150px);
            }

            .config-card {
                padding: 30px 20px 140px 20px;
                border-radius: 20px;
                margin-bottom: 20px;
            }

            .config-title {
                font-size: 1.5rem;
                margin-bottom: 30px;
            }

            .language-config {
                grid-template-columns: 1fr;
                gap: 30px;
                margin-bottom: 140px;
                padding-bottom: 100px;
            }

            .arrow {
                transform: rotate(90deg);
                margin: 20px auto;
            }

            .language-group {
                width: 100%;
            }

            .multi-select-container {
                z-index: 200;
                position: relative;
            }

            .language-options {
                z-index: 10000;
                position: fixed;
                top: auto;
                bottom: 160px;
                left: 15px;
                right: 15px;
                max-height: 250px;
                border-radius: 16px;
                box-shadow: 0 -10px 40px rgba(79, 70, 229, 0.3);
            }

            .controls {
                position: fixed;
                bottom: 20px;
                left: 15px;
                right: 15px;
                background: white;
                padding: 20px;
                border-radius: 20px;
                box-shadow: 0 -5px 20px rgba(0,0,0,0.1);
                z-index: 1000;
                flex-direction: column;
                gap: 15px;
            }

            .control-btn {
                width: 100%;
                padding: 16px;
                font-size: 16px;
                min-width: auto;
            }

            .status-section {
                margin-top: 20px;
                margin-bottom: 140px;
                position: relative;
                z-index: 100;
            }
        }
    </style>
</head>
<body>
    <!-- 登录页面 -->
    <div id="loginOverlay" class="login-overlay">
        <div class="login-container">
            <h1 class="login-title">🌐 语音同传系统</h1>
            <p class="login-subtitle">专业级多语言实时同传解决方案</p>

            <div class="trial-info">
                <h3>免费试用账号</h3>
                <p>欢迎体验我们的语音同传系统！</p>
                <p>• 支持多种语言实时翻译</p>
                <p>• 专业级同传大屏显示</p>
                <p>• 完整的翻译记录导出</p>

                <div class="credentials">
                    <p><strong>试用账号：</strong> trial</p>
                    <p><strong>试用密码：</strong> 123456</p>
                </div>
            </div>

            <form id="loginForm">
                <div id="errorMessage" class="error-message"></div>

                <div class="form-group">
                    <label for="username">账号</label>
                    <input type="text" id="username" class="form-input" placeholder="请输入账号" value="trial">
                </div>

                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" class="form-input" placeholder="请输入密码" value="123456">
                </div>

                <button type="submit" id="loginBtn" class="login-btn">
                    🚀 开始试用
                </button>
            </form>

            <div class="demo-note">
                💡 这是演示版本，仅供功能体验使用
            </div>
        </div>
    </div>

    <div class="header">
        <h1>🌐语音同传系统</h1>
        <p class="subtitle">专业级多语言实时同传解决方案</p>
    </div>

    <div class="main-content">
        <div class="config-card">
            <div class="config-title">🌍 语言配置</div>
            <div class="language-config">
                <div class="language-group">
                    <label>🎤 源语言 (您说的语言)</label>
                    <select id="fromLang">
                        <option value="zh">🇨🇳 中文 (普通话)</option>
                    </select>
                </div>

                <div class="arrow">⬇️</div>

                <div class="language-group">
                    <label>🔄 目标语言 (可多选)</label>
                    <div class="multi-select-container">
                        <div class="selected-languages" id="selectedLanguages">
                            <span class="placeholder">点击选择目标语言...</span>
                        </div>
                        <div class="language-options" id="languageOptions">
                            <div class="language-option" data-value="en">
                                <input type="checkbox" id="lang-en" value="en">
                                <label for="lang-en">🇺🇸 英语 (English)</label>
                            </div>
                       
                            <div class="language-option" data-value="jp">
                                <input type="checkbox" id="lang-jp" value="jp">
                                <label for="lang-jp">🇯🇵 日语 (日本語)</label>
                            </div>
                            <div class="language-option" data-value="kor">
                                <input type="checkbox" id="lang-kor" value="kor">
                                <label for="lang-kor">🇰🇷 韩语 (한국어)</label>
                            </div>
                            <div class="language-option" data-value="fra">
                                <input type="checkbox" id="lang-fra" value="fra">
                                <label for="lang-fra">🇫🇷 法语 (Français)</label>
                            </div>
                            <div class="language-option" data-value="de">
                                <input type="checkbox" id="lang-de" value="de">
                                <label for="lang-de">🇩🇪 德语 (Deutsch)</label>
                            </div>
                            <div class="language-option" data-value="spa">
                                <input type="checkbox" id="lang-spa" value="spa">
                                <label for="lang-spa">🇪🇸 西班牙语 (Español)</label>
                            </div>
                            <div class="language-option" data-value="ru">
                                <input type="checkbox" id="lang-ru" value="ru">
                                <label for="lang-ru">🇷🇺 俄语 (Русский)</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
            <div class="controls">
                <button id="startBtn" class="control-btn start-btn">🎤 开始同传</button>
                <button id="stopBtn" class="control-btn stop-btn" disabled>⏹️ 停止同传</button>
            </div>

            <div class="status-section">
                <div id="statusBar" class="status-bar status-connected">
                    🚀 准备就绪 - 选择语言后点击开始同传
                </div>
            </div>
        </div>
        
        <div class="audio-visualizer">
            <div class="audio-level">
                <div id="audioLevelBar" class="audio-level-bar"></div>
            </div>
        </div>
    </div>
    


    <!-- 全屏同传大屏 -->
    <div id="fullscreenOverlay" class="fullscreen-overlay">
        <!-- 顶部控制栏 -->
        <div class="fullscreen-header">
            <div class="fullscreen-title">
                <div id="statusIndicator" class="status-indicator"></div>
                🎙️ AI多语言实时同传系统
            </div>
            <div class="fullscreen-controls">
                <div class="control-btn stop" id="fullscreenStopBtn">⏹️ 停止同传</div>
                <div class="control-btn" id="exitFullscreenBtn">❌ 退出大屏</div>
            </div>
        </div>

        <!-- 主显示区域 - 左右分栏 -->
        <div class="fullscreen-content">
            <!-- 左侧 - 实时语音识别 -->
            <div class="speech-recognition-panel">
                <div class="speech-panel-header">
                    🎤 实时语音识别
                </div>
                <div class="speech-content">
                    <div id="speechText" class="speech-text">
                        等待开始录音...
                    </div>
                    <div id="typingIndicator" class="typing-indicator" style="display: none;">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                </div>
            </div>

            <!-- 右侧 - 多语言翻译 -->
            <div class="translations-panel">
                <div class="translations-panel-header">
                    🌍 多语言翻译
                </div>
                <div class="translations-container" id="translationsContainer">
                    <!-- 动态生成的语言翻译块 -->
                </div>
            </div>
        </div>

        <!-- 音频可视化 - 波浪特效 -->
        <div id="audioVisualizer" class="audio-visualizer">
            <div class="wave"></div>
            <div class="wave"></div>
            <div class="wave"></div>
        </div>

        <!-- 音频频谱效果 -->
        <div id="audioBars" class="audio-bars">
            <div class="audio-bar"></div>
            <div class="audio-bar"></div>
            <div class="audio-bar"></div>
            <div class="audio-bar"></div>
            <div class="audio-bar"></div>
            <div class="audio-bar"></div>
            <div class="audio-bar"></div>
            <div class="audio-bar"></div>
        </div>
    </div>

    <!-- 二维码弹窗 -->
    <div id="qrModal" class="qr-modal">
        <div class="qr-modal-content">
            <div class="qr-title">📱 扫码下载同传内容</div>
            <div class="qr-subtitle">
                使用手机扫描下方二维码<br>
                即可下载完整的同传文本内容
            </div>
            <div class="qr-code-container">
                <canvas id="qrCode" class="qr-code" width="200" height="200"></canvas>
            </div>
            <div class="qr-info">
                📄 包含原文和多语言翻译<br>
                💾 TXT格式，支持所有设备打开
            </div>
            <div class="qr-buttons">
                <button class="qr-btn primary" id="directDownloadBtn">💾 直接下载</button>
                <button class="qr-btn" id="closeQrBtn">❌ 退出大屏</button>
            </div>
        </div>
    </div>

    <script>
        class VoiceInterpreter {
            constructor() {
                this.ws = null;
                this.audioContext = null;
                this.analyser = null;
                this.microphone = null;
                this.scriptProcessor = null;
                this.isRecording = false;
                this.audioChunks = [];
                this.recordingStartTime = null;

                // 登录相关元素
                this.loginOverlay = document.getElementById('loginOverlay');
                this.loginForm = document.getElementById('loginForm');
                this.usernameInput = document.getElementById('username');
                this.passwordInput = document.getElementById('password');
                this.loginBtn = document.getElementById('loginBtn');
                this.errorMessage = document.getElementById('errorMessage');
                this.isLoggedIn = false;
                // DOM elements
                this.fromLangSelect = document.getElementById('fromLang');
                this.startBtn = document.getElementById('startBtn');
                this.stopBtn = document.getElementById('stopBtn');
                this.statusBar = document.getElementById('statusBar');
                this.audioLevelBar = document.getElementById('audioLevelBar');

                // Multi-select elements
                this.selectedLanguages = document.getElementById('selectedLanguages');
                this.languageOptions = document.getElementById('languageOptions');
                this.selectedLangs = ['en']; // 默认选择英语

                // 全屏同传大屏元素
                this.fullscreenOverlay = document.getElementById('fullscreenOverlay');
                this.speechText = document.getElementById('speechText');
                this.typingIndicator = document.getElementById('typingIndicator');
                this.translationsContainer = document.getElementById('translationsContainer');
                this.statusIndicator = document.getElementById('statusIndicator');
                this.audioVisualizer = document.getElementById('audioVisualizer');
                this.audioBars = document.getElementById('audioBars');
                this.fullscreenStopBtn = document.getElementById('fullscreenStopBtn');
                this.exitFullscreenBtn = document.getElementById('exitFullscreenBtn');

                // 二维码弹窗元素
                this.qrModal = document.getElementById('qrModal');
                this.qrCode = document.getElementById('qrCode');
                this.directDownloadBtn = document.getElementById('directDownloadBtn');
                this.closeQrBtn = document.getElementById('closeQrBtn');

                // 调试信息
                console.log('DOM元素获取结果:');
                console.log('exitFullscreenBtn:', this.exitFullscreenBtn);
                console.log('qrModal:', this.qrModal);
                console.log('qrCode:', this.qrCode);
                console.log('QRCode库加载状态:', typeof QRCode !== 'undefined' ? '已加载' : '未加载');

                this.isFullscreen = false;
                this.speechContent = ''; // 累积的语音内容
                this.languageBlocks = new Map(); // 存储各语言的翻译块
                this.translationHistory = []; // 存储翻译历史记录

                this.initEventListeners();
                this.connectWebSocket();
                this.updateLanguageTitles();
            }

            initEventListeners() {
                // 登录事件
                this.loginForm.addEventListener('submit', (e) => this.handleLogin(e));

                this.startBtn.addEventListener('click', () => this.startRecording());
                this.stopBtn.addEventListener('click', () => this.stopRecording());
                this.fromLangSelect.addEventListener('change', () => this.updateLanguageTitles());

                // 多选语言事件
                this.selectedLanguages.addEventListener('click', () => this.toggleLanguageOptions());

                // 语言选项事件
                const checkboxes = this.languageOptions.querySelectorAll('input[type="checkbox"]');
                checkboxes.forEach(checkbox => {
                    checkbox.addEventListener('change', (e) => this.handleLanguageSelection(e));
                });

                // 点击外部关闭选项
                document.addEventListener('click', (e) => {
                    if (!this.selectedLanguages.contains(e.target) && !this.languageOptions.contains(e.target)) {
                        this.languageOptions.classList.remove('show');
                        this.selectedLanguages.classList.remove('active');
                    }
                });

                // 全屏同传大屏事件
                this.fullscreenStopBtn.addEventListener('click', () => this.stopRecording());
                this.exitFullscreenBtn.addEventListener('click', () => this.showQrModal());

                // 二维码弹窗事件
                this.directDownloadBtn.addEventListener('click', () => this.downloadTranscript());
                this.closeQrBtn.addEventListener('click', () => this.realExitFullscreen());

                // 点击弹窗外部关闭
                this.qrModal.addEventListener('click', (e) => {
                    if (e.target === this.qrModal) {
                        this.closeQrModal();
                    }
                });

                // ESC键退出全屏或关闭弹窗
                document.addEventListener('keydown', (e) => {
                    if (e.key === 'Escape') {
                        if (this.qrModal.classList.contains('show')) {
                            this.closeQrModal();
                        } else if (this.isFullscreen) {
                            this.showQrModal();
                        }
                    }
                });

                // 初始化默认选择
                this.updateSelectedLanguages();

                // 检查是否有下载参数
                this.checkDownloadParam();
            }

            // 检查URL中的下载参数
            checkDownloadParam() {
                const urlParams = new URLSearchParams(window.location.search);
                const downloadId = urlParams.get('download');

                if (downloadId) {
                    const content = sessionStorage.getItem(`transcript_${downloadId}`);
                    if (content) {
                        // 自动下载文件
                        const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
                        const url = URL.createObjectURL(blob);

                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `同传内容_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.txt`;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        URL.revokeObjectURL(url);

                        // 清理sessionStorage
                        sessionStorage.removeItem(`transcript_${downloadId}`);

                        // 清理URL参数
                        window.history.replaceState({}, document.title, window.location.pathname);

                        console.log('通过二维码下载同传内容');
                    }
                }
            }

            connectWebSocket() {
                // 自动检测WebSocket地址
                const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
                const host = location.host; // 包含端口号
                const wsUrl = `${protocol}//${host}`;

                console.log('正在连接WebSocket:', wsUrl);
                this.ws = new WebSocket(wsUrl);

                this.ws.onopen = () => {
                    this.updateStatus('connected', '已连接到服务器 - 准备开始同传');
                };

                this.ws.onmessage = (event) => {
                    const data = JSON.parse(event.data);
                    this.handleServerMessage(data);
                };

                this.ws.onclose = () => {
                    this.updateStatus('disconnected', '与服务器断开连接');
                };

                this.ws.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    this.updateStatus('error', '连接错误');
                };
            }

            toggleLanguageOptions() {
                this.languageOptions.classList.toggle('show');
                this.selectedLanguages.classList.toggle('active');
            }

            handleLanguageSelection(e) {
                const langCode = e.target.value;
                const isChecked = e.target.checked;

                if (isChecked) {
                    if (!this.selectedLangs.includes(langCode)) {
                        this.selectedLangs.push(langCode);
                    }
                } else {
                    this.selectedLangs = this.selectedLangs.filter(lang => lang !== langCode);
                }

                this.updateSelectedLanguages();
                this.updateLanguageTitles();
            }

            updateSelectedLanguages() {
                const langNames = {
                    'zh': { name: '中文', flag: '🇨🇳' },
                    'en': { name: '英语', flag: '🇺🇸' },
                    'jp': { name: '日语', flag: '🇯🇵' },
                    'kor': { name: '韩语', flag: '🇰🇷' },
                    'fra': { name: '法语', flag: '🇫🇷' },
                    'de': { name: '德语', flag: '🇩🇪' },
                    'spa': { name: '西班牙语', flag: '🇪🇸' },
                    'ru': { name: '俄语', flag: '🇷🇺' }
                };

                // 更新复选框状态
                const checkboxes = this.languageOptions.querySelectorAll('input[type="checkbox"]');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.selectedLangs.includes(checkbox.value);
                });

                // 更新显示的选中语言
                if (this.selectedLangs.length === 0) {
                    this.selectedLanguages.innerHTML = '<span class="placeholder">点击选择目标语言...</span>';
                } else {
                    const tags = this.selectedLangs.map(lang => {
                        const langInfo = langNames[lang];
                        return `<span class="language-tag">
                            ${langInfo.flag} ${langInfo.name}
                            <span class="remove" onclick="window.interpreter.removeLanguage('${lang}')">×</span>
                        </span>`;
                    }).join('');
                    this.selectedLanguages.innerHTML = tags;
                }
            }

            removeLanguage(langCode) {
                this.selectedLangs = this.selectedLangs.filter(lang => lang !== langCode);
                this.updateSelectedLanguages();
                this.updateLanguageTitles();
            }

            updateLanguageTitles() {
                // 语言配置更新后，如果在全屏模式，重新初始化语言块
                if (this.isFullscreen) {
                    this.initializeLanguageBlocks();
                }
            }

            handleServerMessage(data) {
                if (data.type === 'translation' && data.data) {
                    const result = data.data;

                    // 隐藏识别中指示器
                    if (this.typingIndicator) {
                        this.typingIndicator.style.display = 'none';
                    }

                    // 更新全屏同传大屏
                    if (result.original && result.translations) {
                        this.updateSpeechContent(result.original);
                        this.updateTranslations(result.translations);

                        // 记录翻译历史
                        this.addToTranslationHistory(result.original, result.translations, result.fromLang);
                    }

                    console.log('收到多语言翻译结果:', result);
                } else if (data.type === 'session_started') {
                    console.log('实时语音识别会话已建立:', data.sessionId);
                    this.updateStatus('recording', '🎤 实时语音识别已启动 - 请开始说话');

                    // 更新语音文本显示
                    this.speechText.textContent = '🎤 实时语音识别已启动 - 请开始说话';
                } else if (data.type === 'error') {
                    console.error('服务器错误:', data.message);
                    this.updateStatus('error', '❌ ' + data.message);
                }
            }

            // 更新语音内容（累积显示）
            updateSpeechContent(newText) {
                // 移除识别中状态
                this.speechText.classList.remove('recognizing');

                // 累积语音内容
                if (this.speechContent) {
                    this.speechContent += ' ' + newText;
                } else {
                    this.speechContent = newText;
                }

                // 更新显示
                this.speechText.textContent = this.speechContent;

                // 添加识别中状态（为下次识别准备）
                setTimeout(() => {
                    this.speechText.classList.add('recognizing');
                }, 500);

                // 自动滚动到底部
                const speechContentEl = this.speechText.parentElement;
                speechContentEl.scrollTop = speechContentEl.scrollHeight;
            }

            // 更新翻译内容
            updateTranslations(translations) {
                const langNames = {
                    'zh': { name: '中文', flag: '🇨🇳' },
                    'en': { name: '英语', flag: '🇺🇸' },
                    'jp': { name: '日语', flag: '🇯🇵' },
                    'kor': { name: '韩语', flag: '🇰🇷' },
                    'fra': { name: '法语', flag: '🇫🇷' },
                    'de': { name: '德语', flag: '🇩🇪' },
                    'spa': { name: '西班牙语', flag: '🇪🇸' },
                    'ru': { name: '俄语', flag: '🇷🇺' }
                };

                // 为每种语言创建或更新翻译块
                for (const [langCode, translatedText] of Object.entries(translations)) {
                    let langBlock = this.languageBlocks.get(langCode);

                    if (!langBlock) {
                        // 创建新的语言块
                        langBlock = document.createElement('div');
                        langBlock.className = 'language-translation-block';

                        const langInfo = langNames[langCode];
                        langBlock.innerHTML = `
                            <div class="language-header">
                                ${langInfo.flag} ${langInfo.name}
                            </div>
                            <div class="language-text" id="lang-${langCode}"></div>
                        `;

                        this.translationsContainer.appendChild(langBlock);
                        this.languageBlocks.set(langCode, langBlock);
                    }

                    // 更新翻译内容（累积显示）
                    const textElement = langBlock.querySelector('.language-text');
                    const currentText = textElement.textContent;

                    // 添加翻译中动画
                    textElement.classList.add('translating');

                    setTimeout(() => {
                        if (currentText && currentText !== '等待翻译...') {
                            textElement.textContent = currentText + ' ' + translatedText;
                        } else {
                            textElement.textContent = translatedText;
                        }

                        // 移除翻译中动画
                        textElement.classList.remove('translating');

                        // 自动滚动到底部
                        textElement.scrollTop = textElement.scrollHeight;
                    }, 300);
                }
            }

            async startRecording() {
                // 检查登录状态
                if (!this.isLoggedIn) {
                    this.checkLoginStatus();
                    return;
                }

                try {
                    console.log('🎤 正在请求麦克风权限...');
                    const stream = await navigator.mediaDevices.getUserMedia({
                        audio: {
                            sampleRate: 16000,
                            channelCount: 1,
                            echoCancellation: true,
                            noiseSuppression: true
                        }
                    });

                    this.setupAudioContext(stream);
                    this.setupAudioProcessor(stream);

                    this.isRecording = true;
                    this.audioChunks = [];
                    this.recordingStartTime = Date.now();

                    this.startBtn.disabled = true;
                    this.stopBtn.disabled = false;
                    this.updateStatus('recording', '🎤 正在录音 - 请开始说话');

                    // 显示全屏同传大屏
                    this.showFullscreen();

                    // 发送开始实时语音识别请求
                    this.ws.send(JSON.stringify({
                        type: 'start',
                        fromLang: this.fromLangSelect.value,
                        toLangs: this.selectedLangs
                    }));

                } catch (error) {
                    console.error('启动录音失败:', error);

                    let errorMessage = '无法访问麦克风';

                    if (error.name === 'NotAllowedError') {
                        errorMessage = '❌ 麦克风权限被拒绝\n\n解决方案：\n1. 点击浏览器地址栏的🔒图标\n2. 允许麦克风权限\n3. 刷新页面重试';
                    } else if (error.name === 'NotFoundError') {
                        errorMessage = '❌ 未找到麦克风设备\n\n请检查：\n1. 麦克风是否正确连接\n2. 系统音频设置\n3. 其他应用是否占用麦克风';
                    } else if (error.name === 'NotSupportedError') {
                        errorMessage = '❌ 浏览器不支持麦克风访问\n\n请使用：\n• Chrome 47+\n• Firefox 36+\n• Safari 11+\n• Edge 12+';
                    } else {
                        errorMessage = `❌ 麦克风访问失败\n\n错误信息：${error.message}\n\n建议：\n1. 刷新页面重试\n2. 检查浏览器权限设置`;
                    }

                    alert(errorMessage);
                    this.updateStatus('error', '❌ 麦克风访问失败');
                }
            }

            setupAudioContext(stream) {
                try {
                    this.audioContext = new (window.AudioContext || window.webkitAudioContext)({
                        sampleRate: 16000
                    });
                    this.analyser = this.audioContext.createAnalyser();
                    this.microphone = this.audioContext.createMediaStreamSource(stream);

                    this.analyser.fftSize = 256;
                    this.microphone.connect(this.analyser);

                    console.log('音频上下文设置成功，采样率:', this.audioContext.sampleRate);
                    this.updateAudioLevel();
                } catch (error) {
                    console.error('设置音频上下文失败:', error);
                    throw error;
                }
            }

            setupAudioProcessor(stream) {
                try {
                    const bufferSize = 2048;
                    this.scriptProcessor = this.audioContext.createScriptProcessor(bufferSize, 1, 1);

                    this.scriptProcessor.onaudioprocess = (event) => {
                        if (this.isRecording) {
                            try {
                                const inputBuffer = event.inputBuffer;
                                const inputData = inputBuffer.getChannelData(0);

                                // 检查是否有声音
                                let hasSound = false;
                                let maxAmplitude = 0;
                                for (let i = 0; i < inputData.length; i++) {
                                    const amplitude = Math.abs(inputData[i]);
                                    maxAmplitude = Math.max(maxAmplitude, amplitude);
                                    if (amplitude > 0.001) {
                                        hasSound = true;
                                    }
                                }

                                // 累积音频数据
                                const pcmData = this.floatTo16BitPCM(inputData);
                                this.audioChunks.push(pcmData);

                                if (hasSound) {
                                    console.log('检测到声音，最大振幅:', maxAmplitude.toFixed(4));
                                }

                                // 每1.5秒发送一次音频进行翻译（提升识别速度）
                                const currentTime = Date.now();
                                if (currentTime - this.recordingStartTime >= 1500) {
                                    this.sendAccumulatedAudio();
                                    this.recordingStartTime = currentTime;
                                }

                                // 限制音频块数量
                                if (this.audioChunks.length > 100) {
                                    console.log('音频块过多，提前发送');
                                    this.sendAccumulatedAudio();
                                    this.recordingStartTime = Date.now();
                                }
                            } catch (error) {
                                console.error('处理音频数据时出错:', error);
                            }
                        }
                    };

                    this.microphone.connect(this.scriptProcessor);
                    this.scriptProcessor.connect(this.audioContext.destination);

                    console.log('音频处理器设置成功');
                } catch (error) {
                    console.error('设置音频处理器失败:', error);
                    throw error;
                }
            }

            sendAccumulatedAudio() {
                if (this.audioChunks.length === 0 || this.ws.readyState !== WebSocket.OPEN) {
                    return;
                }

                try {
                    // 合并所有音频块
                    const totalLength = this.audioChunks.reduce((sum, chunk) => sum + chunk.length, 0);
                    const maxSize = 64000;
                    const actualSize = Math.min(totalLength, maxSize);
                    const combinedAudio = new Uint8Array(actualSize);
                    let offset = 0;

                    for (const chunk of this.audioChunks) {
                        if (offset >= actualSize) break;
                        const copySize = Math.min(chunk.length, actualSize - offset);
                        combinedAudio.set(chunk.subarray(0, copySize), offset);
                        offset += copySize;
                    }

                    // 转换为base64
                    const base64Data = this.arrayBufferToBase64(combinedAudio);

                    // 发送音频数据到实时语音识别
                    this.ws.send(JSON.stringify({
                        type: 'audio',
                        audioData: base64Data
                    }));

                    console.log(`发送音频数据: ${combinedAudio.length} 字节`);

                    // 显示识别中指示器
                    if (this.typingIndicator) {
                        this.typingIndicator.style.display = 'inline-block';
                    }

                    // 清空音频缓存
                    this.audioChunks = [];
                } catch (error) {
                    console.error('发送音频数据失败:', error);
                    this.audioChunks = [];
                }
            }

            arrayBufferToBase64(buffer) {
                let binary = '';
                const chunkSize = 8192;

                for (let i = 0; i < buffer.length; i += chunkSize) {
                    const chunk = buffer.subarray(i, Math.min(i + chunkSize, buffer.length));
                    binary += String.fromCharCode.apply(null, chunk);
                }

                return btoa(binary);
            }

            floatTo16BitPCM(input) {
                const buffer = new ArrayBuffer(input.length * 2);
                const view = new DataView(buffer);
                let offset = 0;

                for (let i = 0; i < input.length; i++, offset += 2) {
                    let sample = Math.max(-1, Math.min(1, input[i]));
                    sample *= 1.5; // 增强信号
                    sample = Math.max(-1, Math.min(1, sample));
                    const intSample = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;
                    view.setInt16(offset, intSample, true);
                }

                return new Uint8Array(buffer);
            }

            updateAudioLevel() {
                if (!this.analyser || !this.isRecording) return;

                const dataArray = new Uint8Array(this.analyser.frequencyBinCount);
                this.analyser.getByteFrequencyData(dataArray);

                const average = dataArray.reduce((a, b) => a + b) / dataArray.length;
                const percentage = (average / 255) * 100;

                this.audioLevelBar.style.width = percentage + '%';

                requestAnimationFrame(() => this.updateAudioLevel());
            }

            stopRecording() {
                this.isRecording = false;

                // 发送剩余的音频数据
                if (this.audioChunks.length > 0) {
                    this.sendAccumulatedAudio();
                }

                if (this.scriptProcessor) {
                    this.scriptProcessor.disconnect();
                    this.scriptProcessor = null;
                }

                if (this.microphone) {
                    this.microphone.disconnect();
                }

                if (this.audioContext) {
                    this.audioContext.close();
                    this.audioContext = null;
                }

                this.startBtn.disabled = false;
                this.stopBtn.disabled = true;
                this.updateStatus('connected', '同传已停止 - 点击开始继续');

                // 如果没有翻译记录，显示停止状态
                const hasTranslations = this.translationArea.querySelectorAll('.translation-item').length > 0;
                if (!hasTranslations && this.emptyState) {
                    this.emptyState.textContent = '录音已停止，点击"开始同传"继续...';
                }

                if (this.ws.readyState === WebSocket.OPEN) {
                    this.ws.send(JSON.stringify({ type: 'stop' }));
                }
            }

            // 全屏同传大屏相关方法
            showFullscreen() {
                this.isFullscreen = true;
                this.fullscreenOverlay.classList.add('show');
                document.body.style.overflow = 'hidden';

                // 重置内容
                this.speechContent = '';
                this.speechText.textContent = '🎤 正在监听，请开始说话...';
                this.translationsContainer.innerHTML = '';
                this.languageBlocks.clear();

                // 为选中的语言创建翻译块
                this.initializeLanguageBlocks();

                // 启动波浪特效
                this.audioVisualizer.classList.add('active');
                this.audioBars.classList.add('active');
                this.speechText.classList.add('recognizing');

                console.log('进入全屏同传大屏模式');
            }

            exitFullscreen() {
                this.isFullscreen = false;
                this.fullscreenOverlay.classList.remove('show');
                document.body.style.overflow = '';

                // 清理动画状态
                this.audioVisualizer.classList.remove('active');
                this.audioBars.classList.remove('active');
                this.speechText.classList.remove('recognizing');

                console.log('退出全屏同传大屏模式');
            }

            // 真正的退出全屏（从二维码弹窗调用）
            realExitFullscreen() {
                this.exitFullscreen();
                this.closeQrModal();
            }

            initializeLanguageBlocks() {
                const langNames = {
                    'zh': { name: '中文', flag: '🇨🇳' },
                    'en': { name: '英语', flag: '🇺🇸' },
                    'jp': { name: '日语', flag: '🇯🇵' },
                    'kor': { name: '韩语', flag: '🇰🇷' },
                    'fra': { name: '法语', flag: '🇫🇷' },
                    'de': { name: '德语', flag: '🇩🇪' },
                    'spa': { name: '西班牙语', flag: '🇪🇸' },
                    'ru': { name: '俄语', flag: '🇷🇺' }
                };

                // 为每个选中的目标语言创建翻译块
                this.selectedLangs.forEach(langCode => {
                    const langBlock = document.createElement('div');
                    langBlock.className = 'language-translation-block';

                    const langInfo = langNames[langCode];
                    langBlock.innerHTML = `
                        <div class="language-header">
                            ${langInfo.flag} ${langInfo.name}
                        </div>
                        <div class="language-text" id="lang-${langCode}">等待翻译...</div>
                    `;

                    this.translationsContainer.appendChild(langBlock);
                    this.languageBlocks.set(langCode, langBlock);
                });
            }

            // 添加到翻译历史记录
            addToTranslationHistory(originalText, translations, fromLang) {
                const timestamp = new Date().toLocaleString('zh-CN');
                const historyItem = {
                    timestamp: timestamp,
                    original: originalText,
                    translations: translations,
                    fromLang: fromLang
                };
                this.translationHistory.push(historyItem);
            }

            // 显示二维码弹窗
            showQrModal() {
                console.log('点击退出大屏，翻译历史记录数量:', this.translationHistory.length);
                console.log('翻译历史记录:', this.translationHistory);

                if (this.translationHistory.length === 0) {
                    // 如果没有翻译记录，创建一个示例记录用于演示
                    const demoContent = {
                        timestamp: new Date().toLocaleString('zh-CN'),
                        original: '演示内容：欢迎使用AI语音同传系统',
                        translations: {
                            'en': 'Demo content: Welcome to AI voice simultaneous interpretation system',
                            'jp': 'デモコンテンツ：AI音声同時通訳システムへようこそ'
                        },
                        fromLang: 'zh'
                    };
                    this.translationHistory.push(demoContent);
                    console.log('添加了演示内容');
                }

                // 生成下载链接
                const downloadUrl = this.generateDownloadUrl();
                console.log('生成的下载链接:', downloadUrl);

                // 检查canvas元素
                console.log('Canvas元素:', this.qrCode);
                console.log('Canvas尺寸:', this.qrCode.width, 'x', this.qrCode.height);

                // 生成二维码
                this.generateQRCode(downloadUrl);

                // 显示弹窗
                this.qrModal.classList.add('show');

                console.log('显示二维码弹窗');
            }

            // 关闭二维码弹窗
            closeQrModal() {
                this.qrModal.classList.remove('show');
                console.log('关闭二维码弹窗');
            }

            // 生成下载URL
            generateDownloadUrl() {
                const content = this.generateTranscriptContent();
                const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
                const url = URL.createObjectURL(blob);

                // 创建一个临时的下载链接，用于二维码
                const baseUrl = window.location.origin + window.location.pathname;
                const downloadId = Date.now().toString();

                // 存储到sessionStorage，用于后续下载
                sessionStorage.setItem(`transcript_${downloadId}`, content);

                return `${baseUrl}?download=${downloadId}`;
            }

            // 生成二维码
            generateQRCode(url) {
                console.log('开始生成二维码，URL:', url);

                // 使用本地生成方案
                this.generateLocalQRCode(url);
            }

            // 本地生成简单的二维码样式
            generateLocalQRCode(url) {
                const ctx = this.qrCode.getContext('2d');
                ctx.clearRect(0, 0, 200, 200);

                // 绘制背景
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(0, 0, 200, 200);

                // 绘制边框
                ctx.strokeStyle = '#000000';
                ctx.lineWidth = 2;
                ctx.strokeRect(10, 10, 180, 180);

                // 绘制简单的二维码样式图案
                this.drawQRPattern(ctx);

                // 在中心显示下载提示
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(70, 70, 60, 60);
                ctx.strokeRect(70, 70, 60, 60);

                ctx.fillStyle = '#000000';
                ctx.font = 'bold 12px Arial';
                ctx.textAlign = 'center';
                ctx.fillText('📱', 100, 90);
                ctx.font = '10px Arial';
                ctx.fillText('扫码', 100, 105);
                ctx.fillText('下载', 100, 118);

                // 添加点击事件
                this.qrCode.style.cursor = 'pointer';
                this.qrCode.onclick = () => {
                    // 复制链接到剪贴板
                    this.copyToClipboard(url);
                };

                console.log('本地二维码生成完成');
            }

            // 绘制二维码样式图案
            drawQRPattern(ctx) {
                ctx.fillStyle = '#000000';

                // 绘制角落的定位图案
                this.drawCornerPattern(ctx, 15, 15);      // 左上
                this.drawCornerPattern(ctx, 155, 15);     // 右上
                this.drawCornerPattern(ctx, 15, 155);     // 左下

                // 绘制随机点阵图案
                for (let i = 0; i < 20; i++) {
                    for (let j = 0; j < 20; j++) {
                        // 避开角落区域和中心区域
                        if ((i < 4 && j < 4) || (i < 4 && j > 15) || (i > 15 && j < 4) ||
                            (i > 6 && i < 13 && j > 6 && j < 13)) {
                            continue;
                        }

                        // 随机生成点阵
                        if (Math.random() > 0.5) {
                            ctx.fillRect(20 + i * 8, 20 + j * 8, 6, 6);
                        }
                    }
                }
            }

            // 绘制角落定位图案
            drawCornerPattern(ctx, x, y) {
                // 外框
                ctx.fillRect(x, y, 25, 25);
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(x + 2, y + 2, 21, 21);

                // 内框
                ctx.fillStyle = '#000000';
                ctx.fillRect(x + 6, y + 6, 13, 13);
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(x + 8, y + 8, 9, 9);

                // 中心点
                ctx.fillStyle = '#000000';
                ctx.fillRect(x + 10, y + 10, 5, 5);
            }

            // 复制到剪贴板
            copyToClipboard(text) {
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(text).then(() => {
                        alert('下载链接已复制到剪贴板！\n请在手机浏览器中粘贴访问');
                    }).catch(() => {
                        this.showLinkDialog(text);
                    });
                } else {
                    this.showLinkDialog(text);
                }
            }

            // 显示链接对话框
            showLinkDialog(url) {
                const shortUrl = url.length > 50 ? url.substring(0, 50) + '...' : url;
                alert(`请复制以下链接在手机浏览器中打开：\n\n${shortUrl}\n\n或点击"直接下载"按钮`);
            }

            // 显示文本链接作为备用方案
            showTextLink(url) {
                console.log('显示文本链接备用方案');
                const ctx = this.qrCode.getContext('2d');
                ctx.clearRect(0, 0, 200, 200);

                // 绘制背景
                ctx.fillStyle = '#f8f9fa';
                ctx.fillRect(0, 0, 200, 200);

                // 绘制边框
                ctx.strokeStyle = '#dee2e6';
                ctx.lineWidth = 2;
                ctx.strokeRect(1, 1, 198, 198);

                // 绘制文本
                ctx.fillStyle = '#495057';
                ctx.font = 'bold 16px Arial';
                ctx.textAlign = 'center';
                ctx.fillText('📱', 100, 50);

                ctx.font = '12px Arial';
                ctx.fillText('点击复制下载链接', 100, 80);
                ctx.fillText('在手机浏览器中打开', 100, 100);

                ctx.fillStyle = '#007bff';
                ctx.font = 'bold 14px Arial';
                ctx.fillText('点击这里', 100, 130);

                ctx.fillStyle = '#6c757d';
                ctx.font = '10px Arial';
                ctx.fillText('或使用下方直接下载按钮', 100, 160);

                // 添加点击提示
                this.qrCode.style.cursor = 'pointer';
                this.qrCode.onclick = () => {
                    this.copyToClipboard(url);
                };
            }

            // 直接下载同传内容
            downloadTranscript() {
                const content = this.generateTranscriptContent();
                const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
                const url = URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = `同传内容_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.txt`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);

                this.closeQrModal();
                console.log('开始下载同传内容');
            }

            // 生成同传内容文本
            generateTranscriptContent() {
                const langNames = {
                    'zh': '中文',
                    'en': '英语',
                    'jp': '日语',
                    'kor': '韩语',
                    'fra': '法语',
                    'de': '德语',
                    'spa': '西班牙语',
                    'ru': '俄语'
                };

                let content = '=== 语音同传记录 ===\n';
                content += `生成时间: ${new Date().toLocaleString('zh-CN')}\n`;
                content += `记录条数: ${this.translationHistory.length}\n\n`;

                this.translationHistory.forEach((item, index) => {
                    content += `--- 第${index + 1}条记录 ---\n`;
                    content += `时间: ${item.timestamp}\n`;
                    content += `原文 (${langNames[item.fromLang] || item.fromLang}): ${item.original}\n\n`;

                    content += '翻译结果:\n';
                    for (const [langCode, translation] of Object.entries(item.translations)) {
                        content += `${langNames[langCode] || langCode}: ${translation}\n`;
                    }
                    content += '\n';
                });

                return content;
            }

            updateStatus(type, message) {
                if (this.statusBar) {
                    this.statusBar.className = `status-bar status-${type}`;
                    this.statusBar.textContent = message;
                }

                // 更新全屏状态指示器和波浪特效（添加空值检查）
                if (type === 'recording') {
                    if (this.statusIndicator) this.statusIndicator.classList.add('recording');
                    if (this.audioVisualizer) this.audioVisualizer.classList.add('active');
                    if (this.audioBars) this.audioBars.classList.add('active');
                    if (this.speechText) this.speechText.classList.add('recognizing');
                } else {
                    if (this.statusIndicator) this.statusIndicator.classList.remove('recording');
                    if (this.audioVisualizer) this.audioVisualizer.classList.remove('active');
                    if (this.audioBars) this.audioBars.classList.remove('active');
                    if (this.speechText) this.speechText.classList.remove('recognizing');
                }
            }

            // 登录相关方法
            handleLogin(e) {
                e.preventDefault();

                const username = this.usernameInput.value.trim();
                const password = this.passwordInput.value.trim();

                // 清除之前的错误信息
                this.hideError();

                // 验证输入
                if (!username || !password) {
                    this.showError('请输入账号和密码');
                    return;
                }

                // 禁用登录按钮
                this.loginBtn.disabled = true;
                this.loginBtn.textContent = '🔄 登录中...';

                // 模拟登录验证
                setTimeout(() => {
                    if (this.validateCredentials(username, password)) {
                        this.loginSuccess();
                    } else {
                        this.loginFailed();
                    }
                }, 1000);
            }

            validateCredentials(username, password) {
                // 试用账号验证
                const validCredentials = [
                    { username: 'demo', password: '123456' },
                    { username: 'test', password: '123456' },
                    { username: 'trial', password: '123456' }
                ];

                return validCredentials.some(cred =>
                    cred.username === username && cred.password === password
                );
            }

            loginSuccess() {
                this.isLoggedIn = true;
                this.loginBtn.textContent = '✅ 登录成功';

                // 延迟隐藏登录页面
                setTimeout(() => {
                    this.loginOverlay.classList.add('hidden');
                    this.showWelcomeMessage();
                }, 800);
            }

            loginFailed() {
                this.loginBtn.disabled = false;
                this.loginBtn.textContent = '🚀 开始试用';
                this.showError('账号或密码错误，请使用试用账号：demo / 123456');

                // 清空密码输入框
                this.passwordInput.value = '';
                this.passwordInput.focus();
            }

            showError(message) {
                this.errorMessage.textContent = message;
                this.errorMessage.classList.add('show');
            }

            hideError() {
                this.errorMessage.classList.remove('show');
            }

            showWelcomeMessage() {
                // 更新状态栏显示欢迎信息
                this.updateStatus('connected', '🎉 欢迎使用语音同传系统！请选择语言后开始体验');
            }

            checkLoginStatus() {
                // 检查是否已登录，如果未登录则显示登录页面
                if (!this.isLoggedIn) {
                    this.loginOverlay.classList.remove('hidden');
                }
            }

            // 测试麦克风权限
            async testMicrophone() {
                try {
                    console.log('🔍 开始测试麦克风权限...');

                    // 直接尝试获取权限
                    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    console.log('✅ 麦克风权限测试成功');

                    // 立即停止流
                    stream.getTracks().forEach(track => track.stop());

                    return true;
                } catch (error) {
                    console.error('❌ 麦克风权限测试失败:', error);
                    return false;
                }
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async () => {
            window.interpreter = new VoiceInterpreter();

            // 检查登录状态
            window.interpreter.checkLoginStatus();

            // 预先测试麦克风权限（不强制要求）
            setTimeout(async () => {
                const microphoneAvailable = await window.interpreter.testMicrophone();
                if (!microphoneAvailable) {
                    console.warn('⚠️ 麦克风权限预检查失败，用户点击开始录音时会再次尝试');
                }
            }, 1000);
        });
    </script>
</body>
</html>
